package ar.com.globallogic.promomr.domain;

import java.util.Date;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

import ar.com.globallogic.promomr.exceptions.ForbiddenContentException;

@Document(collection="publications")
public class Publication {

	@Id
	private String id;
	
	@DBRef
	private Content content;
	
	@DBRef
	private User owner;
	
	private PublicationState state;
	
	private ContentFiltersChain filters;
	
	public Publication(User owner, Content content){
		this.owner = owner;
		this.content = content;
		this.state = new UploadedState();
		this.filters = new ContentFiltersChain();
	}

	public void publish(){
		this.state.publish(this);
	}
	
	public void publishAt(Date publicationDate){
		this.state.publishAt(this, publicationDate);
	}
	
	public void cancel(){
		this.state.cancel(this);
	}
	
	public Content getContentForUser(User user){
		if(isUserOwner(user) || filters.passes(user)){
			return this.content;
		}
		throw new ForbiddenContentException(this.content.getName(), user.getUserName());
	}

	private boolean isUserOwner(User user) {
		return this.owner.getId().equals(user.getId());
	}
	
	public void removeFilters(){
		this.filters.removeFilters();
	}
	
	public void addFilter(ContentFilter filter){
		this.filters.addFilter(filter);
	}
	
	public String getId(){
		return this.id;
	}
	
	public void setId(String id){
		this.id = id;
	}

	public PublicationState getState() {
		return state;
	}
	
	public void setState(PublicationState state) {
		this.state = state;
	}
	
	public Content getContent(){
		return this.content;
	}
	
	public void setContent(Content content){
		this.content = content;
	}
	
	public User getOwner(){
		return this.owner;
	}
	
	public void setOwner(User owner){
		this.owner = owner;
	}
	
	public ContentFiltersChain getFilters(){
		return this.filters;
	}
	
	public void setFilters(ContentFiltersChain filters){
		this.filters = filters;
	}
	
}
